package com.ai.mall.controller.front;

import com.ai.mall.entity.CartEntity;
import com.ai.mall.entity.UsersEntity;
import com.ai.mall.service.CartService;
import com.ai.mall.utils.R;
import com.ai.mall.vo.req.AddCartProductInfoRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    // 添加商品到购物车接口
    @PostMapping("/add")
    public R addToCart(@RequestBody AddCartProductInfoRequest productInfo, HttpSession session) {
        UsersEntity userInfo = (UsersEntity) session.getAttribute("user");
        if (userInfo == null) {
            return R.error("请先登录");
        }
        // 调用业务逻辑添加商品到购物车，示例返回空字符串
        String result = cartService.addToCart(productInfo, userInfo);

        // 根据业务逻辑的结果返回相应的R对象
        if ("success".equals(result)) {
            return R.ok("商品添加成功");
        } else {
            return R.error("商品添加失败");
        }
    }

    // 从购物车移除商品接口
    @DeleteMapping("/remove/{productId}")
    public R removeFromCart(@PathVariable Integer productId, HttpSession session) {
        UsersEntity userInfo = (UsersEntity) session.getAttribute("user");
        if (userInfo == null) {
            return R.error("请先登录");
        }
        // 调用业务逻辑从购物车移除商品，示例返回空字符串
        return cartService.removeFromCart(productId, userInfo);
    }

    // 更新购物车中商品数量接口
    @PutMapping("/update_quantity/{productId}")
    public R updateProductQuantity(@PathVariable Integer productId, @RequestParam Integer quantity, HttpSession session) {
        UsersEntity userInfo = (UsersEntity) session.getAttribute("user");
        if (userInfo == null) {
            return R.error("请先登录");
        }
        // 调用业务逻辑更新购物车中商品数量，示例返回空字符串
        return cartService.updateProductQuantity(productId, quantity, userInfo);
    }

    // 获取购物车商品列表接口
    @GetMapping
    public R getCartProducts(HttpSession session) {
        UsersEntity userInfo = (UsersEntity) session.getAttribute("user");
        if (userInfo == null) {
            return R.error("请先登录");
        }
        // 调用业务逻辑获取购物车商品列表，示例返回空列表
        List<CartEntity> cartEntities = cartService.getCartProducts(userInfo);
        return R.ok().put("data", cartEntities);
    }
}